<?php
namespace app\rbac\controller;
use app\rbac\model\RoleM;
use app\rbac\model\PrivilegeM;
use think\Db;
use think\Session;
use app\base\controller\Base;

class Role extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        if($this->request->isPost())
        {
            $data = $this->request->post();
            $model = new RoleM();
            $model->add($data);
            return json(['code'=>$model->code,'msg'=>$model->msg]);
        }
        $pModel = new PrivilegeM();
        $priData = $pModel->getCatTree();
        $this->assign(array(
            '_page_title'=>'添加角色',
            '_page_title_english'=>'Role add',
            '_btn_title'=>'角色列表',
            '_btn_link'=>'lst',
            '_page_ico'=>' iconfa-sitemap',
            'priData'=>$priData,
        ));
        return $this->fetch();
    }



    /**
     * 编辑页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        if($this->request->isPost())
        {
            $data = $this->request->post();
            $model = new RoleM();
            $model->edit($data);
            return json(['code'=>$model->code,'msg'=>$model->msg]);
        }
        $pModel = new PrivilegeM();
        $priData = $pModel->getCatTree();
        $data = Db::table('role')
            ->alias('r')
            ->field("r.id,r.role_name,GROUP_CONCAT(rp.pri_id) as pri_ids")
            ->join('role_pri rp','rp.role_id = r.id','LEFT')
            ->where(['r.id'=>$id,'r.is_usable'=>1])
            ->group('r.id')
            ->find();
        $data['pri_ids'] = explode(',',$data['pri_ids'] );
        $this->assign(array(
            '_page_title'=>'编辑角色',
            '_page_title_english'=>'Role edit',
            '_btn_title'=>'角色列表',
            '_btn_link'=>url('lst'),
            '_page_ico'=>' iconfa-sitemap',
            'data'=>$data,
            'priData'=>$priData,
        ));
        return $this->fetch();
    }

    /**
     * 获取全部数据
     * @return mixed
     */
    public function lst()
    {
        $model = new RoleM();
        $data = $model->lst();
        $this->assign(array(
            '_page_title'=>'角色列表',
            '_page_title_english'=>'Role list',
            '_btn_title'=>'添加角色',
            '_btn_link'=>url('add'),
            '_page_ico'=>' iconfa-sitemap',
            'data'=>$data,
        ));
        return $this->fetch();
    }


    /**
     * 删除数据
     * @param $id
     */
    public function del()
    {
        $id = $this->request->post('id');
        $model = new RoleM();
        $model->del($id);
        return json(['code'=>$model->code,'msg'=>$model->msg]);
    }
}
